/*
 *    Copyright (c) 2018-2025, lengleng All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: lengleng (wangiegie@gmail.com)
 */
package com.pig4cloud.pig.mt.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pig4cloud.pig.common.core.exception.CheckedException;
import com.pig4cloud.pig.mt.common.api.constant.PageConstant;
import com.pig4cloud.pig.mt.common.api.utils.Query;
import com.pig4cloud.pig.mt.entity.WxArticle;
import com.pig4cloud.pig.mt.enums.ArticleTypeEnum;
import com.pig4cloud.pig.mt.mapper.WxArticleMapper;
import com.pig4cloud.pig.mt.service.WxArticleService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * CMS文章中心
 *
 * @author JLM
 * @date 2021-03-05 11:45:08
 */
@Service
public class WxArticleServiceImpl extends ServiceImpl<WxArticleMapper, WxArticle> implements WxArticleService {
	private static final String ID_PLACEHOLDER = "${articleId}";

	/**
	 * 查询文章列表时返回的字段（过滤掉详情字段以加快速度）
	 */
	private static final String LIST_FILEDS = "id,summary,image,sub_category,update_time,title,type,tags,create_time,target_link,open_count,category";
	@Autowired
	WxArticleMapper articleMapper;

	@Override
	public IPage queryPage(Map<String, Object> params) {
		String title = (String) params.get("title");
		String type = (String) params.get("type");
		String category = (String) params.get("category");
		String subCategory = (String) params.get("subCategory");
		IPage<WxArticle> page = this.page(
				new Query<WxArticle>().getPage(params),
				new QueryWrapper<WxArticle>()
						.select(LIST_FILEDS)
						.eq(!StringUtils.isEmpty(type), "type", type)
						.like(!StringUtils.isEmpty(category), "category", category)
						.like(!StringUtils.isEmpty(subCategory), "sub_category", subCategory)
						.like(!StringUtils.isEmpty(title), "title", title)
		);

		return page;
	}

	/**
	 * 查询文章详情，每次查询后增加点击次数
	 *
	 * @param id
	 * @return
	 */
	@Override
	public WxArticle findById(String id) {
		if (StringUtils.isEmpty(id)) {
			return null;
		}
		WxArticle article = articleMapper.selectById(id);
		if (article != null) {
			articleMapper.addOpenCount(id);
		}
		return article;
	}


	/**
	 * 添加或编辑文章,同名文章不可重复添加
	 *
	 * @param article
	 */

	@Override
	public boolean save(WxArticle article) {
		article.setUpdateTime(new Date());
		if (StringUtils.isNotEmpty(article.getId())) {
			articleMapper.updateById(article);
		} else {
			String title = article.getTitle();
			int count = articleMapper.selectCount(
					new QueryWrapper<WxArticle>().eq("title", title)
							.eq("category", article.getCategory())
							.eq("sub_category", article.getSubCategory())
			);
			if (count > 0) {
				throw new CheckedException("同目录下文章[" + title + "]已存在，不可重复添加");
			}
			article.setCreateTime(new Date());
			articleMapper.insert(article);
		}
		String targetLink = article.getTargetLink();
		if (targetLink.indexOf(ID_PLACEHOLDER) > -1) {
			article.setTargetLink(targetLink.replace(ID_PLACEHOLDER, article.getId() + ""));
			articleMapper.updateById(article);
		}
		return true;
	}

	/**
	 * 按条件分页查询
	 *
	 * @param title
	 * @param page
	 * @return
	 */
	@Override
	public IPage<WxArticle> getArticles(String title, int page) {
		return this.page(new Page<WxArticle>(page, PageConstant.PAGE_SIZE_SMALL),
				new QueryWrapper<WxArticle>().like(!StringUtils.isEmpty("title"), "title", title)
						.select(LIST_FILEDS)
						.orderBy(true, false, "update_time"));
	}

	/**
	 * 查看目录，不返回文章详情字段
	 *
	 * @param articleType
	 * @param category
	 * @return
	 */
	@Override
	public List<WxArticle> selectCategory(ArticleTypeEnum articleType, String category) {
		return this.list(new QueryWrapper<WxArticle>()
				.select(LIST_FILEDS)
				.eq("type", articleType.getValue())
				.eq("category", category));
	}

	/**
	 * 文章查找，不返回文章详情字段
	 *
	 * @param articleType
	 * @param category
	 * @param keywords
	 * @return
	 */
	@Override
	public List<WxArticle> search(ArticleTypeEnum articleType, String category, String keywords) {
		return this.list(new QueryWrapper<WxArticle>()
				.select(LIST_FILEDS)
				.eq("type", articleType.getValue())
				.eq(!StringUtils.isEmpty(category), "category", category)
				.and(i -> i.like("summary", keywords).or().like("title", keywords)));
	}
}
